package com.jnu.myllm.ui;

import com.jnu.myllm.entity.User;
import com.jnu.myllm.server.UserService;
import com.jnu.myllm.ui.vo.Result;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.UUID;

@Controller
@CrossOrigin(origins = "*", exposedHeaders = "*", allowedHeaders = "*")
public class UserController {
    private static final Logger log = LoggerFactory.getLogger(UserController.class);
    @Autowired
    private UserService userService;
    // 配置变量：头像上传路径
    @Value("${my.upload.user}")
    private String uploadDir;
    @PostMapping("/user/reg")
    @ResponseBody
    public Result reg(String nickname, String loginname, String loginpwd, MultipartFile imgfile)throws IOException {
        User user = new User();
        user.setNickName(nickname);
        user.setLoginName(loginname);
        user.setLoginPwd(loginpwd);
        user.setScore(20);
        if (imgfile != null && !imgfile.isEmpty()){
            File dir = new File(uploadDir);
            if(!dir.exists())
                dir.mkdirs();
            System.out.println(imgfile.getOriginalFilename()+"上传到后端");
            // 头像名字是用户名+后缀
            String imgname = loginname
                    +imgfile.getOriginalFilename().substring(imgfile.getOriginalFilename().lastIndexOf("."));
            imgfile.transferTo(new File(uploadDir+"/"+imgname));
            user.setImg(imgname);
        }
        System.out.println(user.getNickName()+"注册成功"+user);
        return new Result(2000,"注册成功",userService.register(user));
    }

    @PostMapping("/user/reg2")
    @ResponseBody
    public Result reg2(@RequestBody User u){
        try{
            u.setScore(20);
            userService.register(u);
            System.out.println(u.getNickName());
            return new Result(2000,"注册成功", u);
        }catch (Exception ex) {
            // 捕获业务层抛出的异常
            return new Result(5000,"注册失败："+ex.getMessage(),null);
        }
    }
    @PostMapping("/user/login")
    @ResponseBody
    public Result login(String loginName, String loginPwd, HttpServletResponse response) {
        log.debug("loginName="+loginName+",loginPwd="+loginPwd);
        log.info("登录请求："+loginName);
        User u = userService.login(loginName, loginPwd);
        if (u == null) {
            return new Result(4001,"用户名或密码错误",null);
        }
        try {
            // 对凭证进行签名（包括一些声明claim）用于身份验证
            JwtBuilder builder = Jwts.builder();
            builder.setId(UUID.randomUUID().toString());
            builder.setIssuedAt(new Date());
            // 过期函数
            builder.setExpiration(new Date(System.currentTimeMillis()+1000*60*60));
            builder.signWith(SignatureAlgorithm.HS256, "111222");
            builder.claim("userId", u.getId());
            builder.claim("nickName",u.getNickName());
            builder.claim("loginName",u.getLoginName());
            builder.claim("score",u.getScore());
            builder.setSubject(u.getId()+"");
            String token = builder.compact();
            //System.out.println(token);
            response.setHeader("Authorization",token);
            log.debug(token);
            log.info("登录成功："+u.getLoginName()+"->"+u.getNickName());
            return new Result(2000,"登录成功",u);
        }catch (Exception ex){
            ex.printStackTrace();
            log.error(loginName+"登录异常："+ex.getMessage());
            return new Result(5000,"登录失败："+ex.getMessage(),null);
        }

    }

}
